package uml.util.listeners;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JComponent;
import javax.swing.JPanel;

import uml.view.UMLContainerView;

/**
 * DragListener allows UMLContainerView objects to be dragged. To simply
 * the user interface, classes that want to be dragged should
 * implement the Dragable interface so users only need to 
 * call their addDragListener method.
 *   
 * @author Neil Obetz
 *
 */

public class DragListener implements MouseListener, MouseMotionListener
{
	private JComponent m_dragablePanel;
	private int m_x;
	private int m_y;
	private boolean inside = false;
	private boolean dragging = false;
	
	/**
	 * Creates a new DragListener.
	 * @param panel the panel to be dragged.
	 */
	public DragListener (JComponent panel)
	{
		m_dragablePanel = panel;
	}
	
	@Override
	public void mouseDragged (MouseEvent e)
	{			
		int x = e.getXOnScreen ();
		int y = e.getYOnScreen ();
		
		int dx, dy;
		
		if ((inside || dragging))
		{
			dx = x-m_x;
			dy = y-m_y;
			m_dragablePanel.setLocation (m_dragablePanel.getX () + dx, m_dragablePanel.getY () + dy);
			m_x = x;
			m_y = y;
		}		
	}

	@Override
	public void mouseMoved (MouseEvent e)
	{
	}

	@Override
	public void mouseClicked (MouseEvent e)
	{
	}

	@Override
	public void mousePressed (MouseEvent e)
	{	
        if (inside)
		{
			dragging = true;
		}
		m_x = e.getXOnScreen ();
		m_y = e.getYOnScreen ();
	}

	@Override
	public void mouseReleased (MouseEvent e)
	{	
		dragging = false;
	}

	@Override
	public void mouseEntered (MouseEvent e)
	{
		inside = true;	
	}	

	@Override
	public void mouseExited (MouseEvent e)
	{
		inside = false;
	}	
}
